package mongodb.general.operator.nodb.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

@Slf4j
public class DateUtils {
    public static final Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
    public static final Pattern datePatternMongo = Pattern.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}");
    public static final String simpleDate = "yyyy-MM-dd HH:mm:ss";
    /**
     * 处理传入的Json参数日期均为字符串的问题
     * 将日期字符串转为Date对象
     * @param
     */
    public static void transformStringToDate(Map<String, Object> map) {
        for (String key : map.keySet()) {
            Object obj = map.get(key);
            if (Objects.nonNull(obj) && obj instanceof String) {
                DateUtils dateUtils = new DateUtils();
                dateUtils.tryTrans(key, map);
            } else if (Objects.nonNull(obj) && obj instanceof List && !((List) obj).isEmpty()) {
                Object subListType = ((List) obj).get(0);
                if (subListType instanceof String) {
                    continue;
                } else if (subListType instanceof Map) {
                    // 嵌套子数组
                    for (Object subListElement : ((List<?>) obj)) {
                        Map<String, Object> subListElement1 = (Map<String, Object>) subListElement;
                        transformStringToDate(subListElement1);
                    }
                }
            }
        }
    }
    /**
     * 字符串为日期就替换掉 否则不处理
     * @param
     */
    private void tryTrans(String key, Map<String, Object> map) {
        String date = (String) map.get(key);
        if (datePattern.matcher(date).find() || datePatternMongo.matcher(date).find()) {
            try {
                if (date.contains("T"))
                    date = date.replace("T", " ");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(simpleDate);
                Date parsedDate = simpleDateFormat.parse(date);
                map.put(key, parsedDate);
            } catch (ParseException e) {
                log.debug("无效的日期 key:{}, value:{} ", key, map.get(key));
            }
        }
    }
}
